<template>
  <el-dialog
    v-model="visible"
    width="70%"
    :before-close="handleClose"
  >
    <div class="preview-container">
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading"><loading /></el-icon>
        <span>加载中...</span>
      </div>

      <!-- PDF预览 -->
      <iframe
        v-else-if="previewType === 'pdf'"
        :src="previewUrl"
        frameborder="0"
        class="preview-iframe"
      ></iframe>

      <!-- 图片预览 -->
      <el-image
        v-else-if="previewType === 'image'"
        :src="previewUrl"
        :preview-src-list="[previewUrl]"
        fit="contain"
        class="preview-image"
      />

      <!-- 文本预览 -->
      <iframe
        v-else-if="previewType === 'text'"
        :src="previewUrl"
        frameborder="0"
        class="preview-iframe"
      ></iframe>

      <!-- Office文档预览 (使用Office Online) -->
      <iframe
        v-else-if="previewType === 'office'"
        :src="officePreviewUrl"
        frameborder="0"
        class="preview-iframe"
      ></iframe>

      <!-- 视频预览 -->
      <video
        v-else-if="previewType === 'video'"
        :src="previewUrl"
        controls
        class="preview-video"
      ></video>

      <!-- 音频预览 -->
      <audio
        v-else-if="previewType === 'audio'"
        :src="previewUrl"
        controls
        class="preview-audio"
      ></audio>

      <!-- 不支持预览 -->
      <div v-else class="unsupported-preview">
        <el-icon><warning /></el-icon>
        <p>不支持预览该类型文件</p>
        <p class="file-info">文件类型: {{ document.fileType }}</p>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" @click="handleDownload">
        <el-icon><Download /></el-icon> 下载
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { Warning, Download } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  document: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:modelValue'])

const visible = ref(null)
const loading = ref(false)
const previewUrl = ref('')
const previewType = ref('')

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    loadPreview()
  }
})

// 监听visible变化
watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 关闭对话框
const handleClose = () => {
  visible.value = false
}

// 获取文件类型
const getFileType = (fileName) => {
  if (!fileName) return ''
  const ext = fileName.toLowerCase().split('.').pop()
  return ext
}

// 判断预览类型
const determinePreviewType = (fileType) => {
  const type = fileType.toLowerCase()
  
  // 图片类型
  if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'ico', 'tiff', 'tif'].includes(type)) {
    return 'image'
  }
  
  // PDF类型
  if (type === 'pdf') {
    return 'pdf'
  }
  
  // 文本类型
  if (['txt', 'md', 'json', 'xml', 'csv', 'log', 'ini', 'conf', 'config', 'js', 'css', 'html', 'htm', 'php', 'py', 'java', 'c', 'cpp', 'cs', 'sql', 'sh', 'bat', 'ps1'].includes(type)) {
    return 'text'
  }
  
  // Office文档类型
  if (['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'rtf', 'odt', 'ods', 'odp'].includes(type)) {
    return 'office'
  }
  
  // 视频类型
  if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'].includes(type)) {
    return 'video'
  }
  
  // 音频类型
  if (['mp3', 'wav', 'ogg', 'flac', 'aac'].includes(type)) {
    return 'audio'
  }
  
  return 'unsupported'
}

// Office Online预览URL
const officePreviewUrl = computed(() => {
  if (previewType.value !== 'office') return ''
  
  // 确保使用完整的URL
  let fullUrl = previewUrl.value
  if (!fullUrl.startsWith('http')) {
    // 如果是相对路径，转换为完整URL
    const baseUrl = window.location.origin
    fullUrl = `${baseUrl}${fullUrl}`
  }
  
  const encodedUrl = encodeURIComponent(fullUrl)
  
  // 使用Office Online预览服务
  // 格式：https://view.officeapps.live.com/op/embed.aspx?src=https://host/api/files/202406/demo.docx
  return `https://view.officeapps.live.com/op/embed.aspx?src=${encodedUrl}`
})

// 调试信息
computed(() => {
  return {
    document: {
      id: props.document.id,
      fileName: props.document.fileName,
      filePath: props.document.filePath,
      fileType: props.document.fileType
    },
    preview: {
      type: previewType.value,
      url: previewUrl.value,
      officeUrl: officePreviewUrl.value
    },
    environment: {
      origin: window.location.origin,
      userAgent: navigator.userAgent,
      timestamp: new Date().toISOString()
    }
  }
})

// 加载预览
const loadPreview = async () => {
  try {
    loading.value = true
    
    // 构建静态文件URL
    const fileType = getFileType(props.document.fileName)
    previewType.value = determinePreviewType(fileType)
    
    // 使用新的API路径：/api/files/{yyyyMM}/{fileName}
    if (props.document.filePath) {
      // 如果filePath已经是完整路径，转换为API路径
      if (props.document.filePath.startsWith('/files/')) {
        // 从 /files/202508/xxx.txt 转换为 /api/files/202508/xxx.txt
        previewUrl.value = props.document.filePath.replace('/files/', '/api/files/')
      } else {
        // 如果filePath是相对路径，构建API路径
        previewUrl.value = `/api/files/${props.document.filePath}`
      }
    } else {
      // 如果没有filePath，构建默认API路径（这种情况不应该发生）
      const currentMonth = new Date().toISOString().slice(0, 7).replace('-', '')
      const guid = crypto.randomUUID()
      previewUrl.value = `/api/files/${currentMonth}/${guid}_${props.document.fileName}`
    }
    
    // 验证URL格式
    const urlPattern = /^\/api\/files\/\d{6}\/[a-f0-9-]+_.+$/
    const isValidUrl = urlPattern.test(previewUrl.value)
    
    console.log('预览配置:', {
      fileType,
      previewType: previewType.value,
      previewUrl: previewUrl.value,
      officePreviewUrl: officePreviewUrl.value,
      originalFilePath: props.document.filePath,
      fileName: props.document.fileName,
      expectedFormat: '/api/files/yyyyMM/{guid}_{文件名}',
      isValidUrl: isValidUrl,
      urlPattern: urlPattern.source
    })
    
    if (!isValidUrl) {
      console.warn('URL格式不符合预期:', previewUrl.value)
    }
    
  } catch (error) {
    console.error('加载预览失败:', error)
    previewType.value = 'error'
  } finally {
    loading.value = false
  }
}

// 下载文件
const handleDownload = () => {
  const link = document.createElement('a')
  link.href = previewUrl.value
  link.download = props.document.fileName || `download.${getFileType(props.document.fileName)}`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>

<style scoped>
.preview-container {
  height: 60vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.loading-container .el-icon {
  font-size: 30px;
  color: var(--el-color-primary);
}

.preview-iframe {
  width: 100%;
  height: 60vh;
  border: none;
}

.preview-image {
  max-width: 100%;
  max-height: 60vh;
}

.preview-video {
  max-width: 100%;
  max-height: 60vh;
}

.preview-audio {
  width: 100%;
  margin: 20px 0;
}

.unsupported-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  padding: 20px;
}

.unsupported-preview .el-icon {
  font-size: 40px;
  color: var(--el-color-warning);
}

.unsupported-preview p {
  margin: 0;
}

.file-info {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.debug-info {
  margin-top: 20px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
  font-size: 12px;
}

.debug-info details {
  cursor: pointer;
}

.debug-info pre {
  margin: 10px 0 0 0;
  white-space: pre-wrap;
  word-break: break-all;
  font-size: 11px;
  color: #666;
}
</style>